<template>
  <el-form ref="pushFrom" :rules="rules" :inline="true" label-width="110px" label-position="left" :model="pushFrom"
           class="demo-form-inline">
    <el-form-item label="公告名称" prop="name">
      <el-input v-model="pushFrom.name" placeholder="请输入公告名称"></el-input>
    </el-form-item>
    <el-form-item label="公告内容">
      <el-upload
          class="upload-file"
          drag
          action="/api/Admin/upload/file"
          accept=".doc,.docx,.pdf"
          name="content"
          :limit="1"
          :before-upload="beforeUpload"
          :on-remove="delFile"
          :on-success="onSuccess"
          :on-exceed="handleExceed"
          :auto-upload="true">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">上传doc/docx/pdf类型的文件<br/>且不超过500kb</div>
      </el-upload>
    </el-form-item>

  </el-form>
</template>

<script>
import admin from "../../api/admin";

export default {
  name: "pushNotice",
  data() {
    return {
      filePath: [],
      pushFrom: {
        name: ''
      },
      rules: {
        name: [{required: true, message: '请输入名字', trigger: 'blur'},]
      }
    }
  },
  methods: {

    confirm() {
      this.$refs.pushFrom.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '添加中请稍后...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          let param = {...this.pushFrom}
          param.filePath = this.filePath
          param.collegeName = this.$store.getters["userStore/userInfo"].collegeName
          admin.AddNotice(param).then(r => {
            this.$refs.pushFrom.resetFields()
            loading.close();
            if (r.data.status === "200") {
              this.$emit("modifyEvent")
              this.$message({
                message: '添加成功',
                type: 'success'
              });
            }
          }).catch(err => {
            loading.close();
            console.error(err)
            this.$message.error('添加失败');
          })
        }
      })

    },
    //删除文件
    delFile(file) {
      admin.DelUploadFile({path: file.response.data.fileInfo.path}).then()
    },
    // 文件上传成功
    onSuccess(res) {
      this.filePath.push(res.data.fileInfo)
    },
    // 超出文件指定个数的钩子函数
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // 上传之前判断文件大小的路由钩子
    beforeUpload(file) {
      if (file.size / 1024 > 500) {
        this.$alert('上传的文件不能大于500kb', '温馨提示', {
          confirmButtonText: '确定'
        });
        return false
      }
    },
  }
}
</script>

<style scoped>

</style>